<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="showSearch">
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable prefix-icon="el-icon-search" placeholder="流程名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation />
      </div>
      <el-row :gutter="10" class="mb8 uifix-crud-opts">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleLoadXml"
          >新增</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            v-permission="['flowable:deployment:remove']"
            type="danger"
            icon="el-icon-delete"
            class="uifix-square-btn"
            :loading="crud.delAllLoading"
            :disabled="crud.selections.length === 0"
            @click="handleDelete(crud.selections)"
          />
        </el-col>
        <el-button
          size="mini"
          icon="el-icon-refresh"
          style="float: right"
          @click="crud.refresh()"
        />
      </el-row>

      <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 320px)" :data="crud.data" style="width: 100%;margin-top: 10px;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="流程编号" align="center" prop="deploymentId" :show-overflow-tooltip="true" />
        <el-table-column label="流程标识" align="center" prop="key" :show-overflow-tooltip="true" />
        <el-table-column label="流程分类" align="center" prop="category" />
        <el-table-column label="流程名称" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-button type="text" @click="handleReadImage(scope.row.deploymentId)">
              <span>{{ scope.row.name }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="业务表单" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-button v-if="scope.row.formId" type="text" @click="handleForm(scope.row.formId)">
              <span>{{ scope.row.formName }}</span>
            </el-button>
            <label v-else>暂无表单</label>
          </template>
        </el-table-column>
        <el-table-column label="流程版本" align="center">
          <template slot-scope="scope">
            <el-tag size="medium">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.suspensionState === 1" type="success">激活</el-tag>
            <el-tag v-if="scope.row.suspensionState === 2" type="warning">挂起</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                更多操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-edit-outline" @click.native="handleLoadXml(scope.row)">
                  编辑
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.formId == null" icon="el-icon-connection" @click.native="handleAddForm(scope.row)">
                  配置表单
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.suspensionState === 1" icon="el-icon-video-pause" @click.native="handleUpdateSuspensionState(scope.row)">
                  挂起
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.suspensionState === 2" icon="el-icon-video-play" @click.native="handleUpdateSuspensionState(scope.row)">
                  激活
                </el-dropdown-item>
                <el-dropdown-item v-permission="['system:deployment:remove']" icon="el-icon-delete" @click.native="handleDelete(scope.row)">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>

    <!-- bpmn20.xml导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xml"
        :headers="upload.headers"
        :action="upload.url + '?name=' + upload.name+'&category='+ upload.category"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          流程名称：<el-input v-model="upload.name" />
          流程分类：<el-input v-model="upload.category" />
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“bpmn20.xml”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 流程图 -->
    <el-dialog :title="readImage.title" :visible.sync="readImage.open" width="70%" append-to-body>
      <!-- <el-image :src="readImage.src"></el-image> -->
      <flow :xml-data="xmlData" />
    </el-dialog>

    <!--表单配置详情-->
    <el-dialog :title="formTitle" :visible.sync="formConfOpen" width="50%" append-to-body>
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="formConf" />
      </div>
    </el-dialog>

    <!--挂载表单-->
    <el-dialog :title="formDeployTitle" :visible.sync="formDeployOpen" width="50%" append-to-body>
      <el-row :gutter="24">
        <el-col :span="10" :xs="24">
          <el-table
            ref="singleTable"
            stripe
            :data="formList"
            border
            highlight-current-row
            style="width: 100%"
            @current-change="handleCurrentChange"
          >
            <el-table-column label="表单编号" align="center" prop="formId" />
            <el-table-column label="表单名称" align="center" prop="formName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="submitFormDeploy(scope.row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <!--          <pagination />-->
        </el-col>
        <el-col :span="14" :xs="24">
          <div v-if="currentRow">
            <parser :key="new Date().getTime()" :form-conf="currentRow" />
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import crudDefinition from '@/api/flowable/definition'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import { updateState, addDeployment, updateDeployment, exportDeployment, definitionStart, readXml, getDeployment } from '@/api/flowable/definition'
import { getToken } from '@/utils/auth'
import { getForm, addDeployForm, listForm } from '@/api/flowable/form'
import Parser from '@/components/parser/Parser'
import flow from '@/views/flowable/task/record/flow'
import pagination from '@brotherCrud/Pagination'
import rrOperation from '@brotherCrud/RR.operation'

const defaultForm = { deploymentId: null, key: null, category: null, deploymentTime: null }

export default {
  name: 'Definition',
  components: { Parser, pagination, flow, rrOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '流程定义',
      url: 'api/flowable/definition',
      crudMethod: { ...crudDefinition }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'flowable:form:add'],
        edit: ['admin', 'flowable:form:edit'],
        del: ['admin', 'flowable:form:del']
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      showSearch: true,
      // 弹出层标题
      title: '',
      formConfOpen: false,
      formTitle: '',
      formDeployOpen: false,
      formDeployTitle: '',
      formList: [],
      formTotal: 0,
      formConf: {}, // 默认表单数据
      readImage: {
        open: false,
        src: ''
      },
      // bpmn.xml 导入
      upload: {
        // 是否显示弹出层（xml导入）
        open: false,
        // 弹出层标题（xml导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        name: null,
        category: null,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/api/flowable/definition/import'
      },
      queryTypeOptions: [
        { key: 'FlowName', display_name: '流程名称' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      },
      formQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 挂载表单到流程实例
      formDeployParam: {
        formId: null,
        deployId: null
      },
      currentRow: null,
      // xml
      xmlData: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.crud.refresh()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加流程定义'
    },
    /** 跳转到流程设计页面 */
    handleLoadXml(row) {
      this.$router.push({ path: '/flowable/definition/model', query: { deployId: row.deploymentId }})
    },
    /** 流程图查看 */
    handleReadImage(deploymentId) {
      this.readImage.title = '流程图'
      this.readImage.open = true
      // this.readImage.src = process.env.VUE_APP_BASE_API + "/flowable/definition/readImage/" + deploymentId;
      // 发送请求，获取xml
      readXml(deploymentId).then(res => {
        this.xmlData = res.data
      })
    },
    /** 表单查看 */
    handleForm(formId) {
      getForm(formId).then(res => {
        this.formTitle = '表单详情'
        this.formConfOpen = true
        this.formConf = JSON.parse(res.data.formContent)
      })
    },
    /** 启动流程 */
    handleDefinitionStart(row) {
      definitionStart(row.id).then(res => {
        this.$message.success(res.msg)
      })
    },
    /** 挂载表单弹框 */
    handleAddForm(row) {
      this.formDeployParam.deployId = row.deploymentId
      this.ListFormDeploy()
    },
    /** 挂载表单列表 */
    ListFormDeploy() {
      listForm(this.formQueryParams).then(res => {
        this.formList = res.content
        this.formTotal = res.totalElements
        this.formDeployOpen = true
        this.formDeployTitle = '挂载表单'
      })
    },

    /** 挂载表单 */
    submitFormDeploy(row) {
      this.formDeployParam.formId = row.formId
      addDeployForm(this.formDeployParam).then(res => {
        this.$message.success(res.msg)
        this.formDeployOpen = false
        this.crud.refresh()
      })
    },
    handleCurrentChange(data) {
      if (data) {
        this.currentRow = JSON.parse(data.formContent)
      }
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row) {
      let state = 1
      if (row.suspensionState === 1) {
        state = 2
      }
      const params = {
        deployId: row.deploymentId,
        state: state
      }
      updateState(params).then(res => {
        this.$message.success(res.msg)
        this.crud.refresh()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDeployment(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改流程定义'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDeployment(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.crud.refresh()
            })
          } else {
            addDeployment(this.form).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.crud.refresh()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(datas) {
      // const ids = row.deploymentId || this.ids;
      // const params = {
      //   deployId: row.deploymentId
      // }

      var deployIds = {}
      var ids = []
      if (datas.length !== undefined) {
        deployIds = datas.map(item => item.deploymentId)
        ids = datas.map(function(data) {
          return { 'id': data.deploymentId }
        })
      } else {
        deployIds = datas.deploymentId
        ids.push({ 'id': datas.deploymentId })
      }
      const crud = this.crud
      this.$confirm('是否确认删除流程定义编号为"' + deployIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        crud.delAllLoading = true
        crud.doDelete(ids)
      }).catch((error) => {
        console.log(error)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有流程定义数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportDeployment(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },
    /** 导入bpmn.xml文件 */
    handleImport() {
      this.upload.title = 'bpmn20.xml文件导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$message.success(response.msg)
      this.crud.refresh()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
